package com.jrx.anytxn.reporting.service.impl;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.entity.CmCustomerAddressInfo;
import com.jrx.anytxn.customer.entity.CmCustomerContactInfo;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerAddressInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerContactInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.bean.CustomerDataBean;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.dto.MrCustomerInfoRes;
import com.jrx.anytxn.reporting.entity.MrCustomerInfo;
import com.jrx.anytxn.reporting.mapper.base.MrCustomerInfoMapper;
import com.jrx.anytxn.reporting.mapper.ext.ExtMrCustomerInfoMapper;
import com.jrx.anytxn.reporting.service.ICustomerDataDealService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：lihm
 * @date ：2019/11/26 20:12
 */
@Service
public class CustomerDataDealServiceImpl implements ICustomerDataDealService {

    Logger logger = LoggerFactory.getLogger(CustomerDataDealServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtCmCustomerFirstLevelMapper extCmCustomerFirstLevelMapper;
    @Resource
    private ExtCmCustomerAddressInfoMapper extCmCustomerAddressInfoMapper;
    @Resource
    private ExtCmCustomerContactInfoMapper extCmCustomerContactInfoMapper;
    @Resource
    private MrCustomerInfoMapper mrCustomerInfoMapper;
    @Resource
    private ExtMrCustomerInfoMapper extMrCustomerInfoMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ICodeTableService codeTableService;

    @Override
    public CustomerDataBean assemCustomerData(CmCustomerSecondLevel secondLevel) throws TxnBizException {
        CustomerDataBean customerDataBean = new CustomerDataBean();
//        String createDate = DateUtils.format(SecondLevel.getCreateTime());
//        String endDate = DateUtils.format(SecondLevel.getUpdateTime());
        MrCustomerInfo lastCust = extMrCustomerInfoMapper.selectMrCustomersByTenantIdAndChannelAndCustomerId(secondLevel.getTenantId(),secondLevel.getChannel(),secondLevel.getCustomerId());

        if(lastCust==null){
            customerDataBean.setFlag(0);//新增
        }else{
            customerDataBean.setFlag(1);//修改
        }
        MrCustomerInfo mrCustomerInfo = BeanMapping.copy(secondLevel, MrCustomerInfo.class);

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        mrCustomerInfo.setBusinessDate(org.getNextProcessingDate());

        if(lastCust==null){
            try {
                mrCustomerInfo.setId(segmentService.getId(ReportingConstant.MR_CUSTOMER_INFO_ID));
            } catch (SegmentException e) {
                logger.error("主键生成错误", e);
                throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
            }
        }
        mrCustomerInfo.setMarriage(secondLevel.getMaritalStatus());//婚姻状态
        mrCustomerInfo.setEducation(secondLevel.getEducation());//学历
        mrCustomerInfo.setIndustry(secondLevel.getCompanyAttribute());//单位所属行业
        if(null != secondLevel.getEducation()){
            switch (secondLevel.getEducation()){
                case ReportingConstant.EDUCATION_99:
                    mrCustomerInfo.setDegree(ReportingConstant.DEGREE_9);
                    break;
                case ReportingConstant.EDUCATION_20:
                    mrCustomerInfo.setDegree(ReportingConstant.DEGREE_4);
                    break;
                case ReportingConstant.EDUCATION_10:
                    mrCustomerInfo.setDegree(ReportingConstant.DEGREE_3);
                    break;
                default:
                    mrCustomerInfo.setDegree(ReportingConstant.DEGREE_0);
                    break;
            }
        }

        //获取一级信息
        CmCustomerFirstLevel firstLevel = extCmCustomerFirstLevelMapper.selectFirstLevelByOrgIdAndCusId(secondLevel.getCustomerId(),secondLevel.getOrganizationId(),secondLevel.getTenantId());
        mrCustomerInfo.setChineseName(firstLevel.getChineseName());//姓名
        mrCustomerInfo.setIdType(firstLevel.getIdType());//B01 证件类型
        mrCustomerInfo.setIdNumber(firstLevel.getIdNumber());//身份证号码
        mrCustomerInfo.setSex(firstLevel.getSex());//性别
        mrCustomerInfo.setBirthDate(firstLevel.getBirthDate());//生日
        mrCustomerInfo.setEcifId(firstLevel.getEcifId());//核心客户号

        //客户地址信息
        List<CmCustomerAddressInfo> addlist = extCmCustomerAddressInfoMapper.selectByCustomerIdAndTenantIdAndChannel(
                secondLevel.getCustomerId(),secondLevel.getTenantId(),secondLevel.getChannel());
        for(CmCustomerAddressInfo addInfo : addlist){
            String addressType = addInfo.getAddressType();
            if(ReportingConstant.ADDRESS_TYPE_1.equals(addressType) ||
                    ReportingConstant.ADDRESS_TYPE_0.equals(addressType)||
                    ReportingConstant.ADDRESS_TYPE_3.equals(addressType)){
                String address = "";
                if(!StringUtils.isBlank(addInfo.getProvince())){
                    PrCodeTable province = codeTableService.findByTypeAndCodeId(ReportingConstant.PROVINCE_TYPE_ID,
                            addInfo.getProvince(),addInfo.getTenantId());
                    if(null != province){
                        address = address + province.getCodeName();
                    }
                }
                if(!StringUtils.isBlank(addInfo.getCity())){
                    PrCodeTable city = codeTableService.findByTypeAndCodeId(ReportingConstant.CITY_TYPE_ID,
                            addInfo.getCity(),addInfo.getTenantId());
                    if(null != city){
                        address = address + city.getCodeName();
                    }
                }
                if(!StringUtils.isBlank(addInfo.getDistrict())){
                    PrCodeTable area = codeTableService.findByTypeAndCodeId(ReportingConstant.AREA_TYPE_ID,
                            addInfo.getDistrict(),addInfo.getTenantId());
                    if(null != area){
                        address = address + area.getCodeName();
                    }
                }
                address = address + addInfo.getAddress();

                //地址需要拼接 省 市 区
                if(ReportingConstant.ADDRESS_TYPE_1.equals(addressType)){
                    mrCustomerInfo.setAddress(address);//通讯地址
                    mrCustomerInfo.setZipcode(addInfo.getZipcode());//邮编
                    mrCustomerInfo.setResideAddress(address);
                    mrCustomerInfo.setResideZipcode(addInfo.getZipcode());
                }else if(ReportingConstant.ADDRESS_TYPE_0.equals(addressType)){
                    mrCustomerInfo.setHouseholdAddress(address);//户籍地址
                }else if(ReportingConstant.ADDRESS_TYPE_3.equals(addressType)){
                    mrCustomerInfo.setCompanyAddress(address);//单位地址
                    mrCustomerInfo.setCompanyZipcode(addInfo.getZipcode());//单位邮编
                }
            }
        }

        //客户配偶信息
        CmCustomerContactInfo cmCustomerContactInfo = new CmCustomerContactInfo();
        cmCustomerContactInfo.setCustomerId(secondLevel.getCustomerId());
        cmCustomerContactInfo.setTenantId(secondLevel.getTenantId());
        cmCustomerContactInfo.setRelationship(ReportingConstant.RELATION_01);//配偶
        List<CmCustomerContactInfo> cmCustomerContactInfoList = extCmCustomerContactInfoMapper.selectByCondSelective(cmCustomerContactInfo);
        if(CollectionUtils.isNotEmpty(cmCustomerContactInfoList)){
            mrCustomerInfo.setSpouseName(cmCustomerContactInfoList.get(0).getChineseName());
            mrCustomerInfo.setSpouseIdType(cmCustomerContactInfoList.get(0).getIdType());
            mrCustomerInfo.setSpouseIdNumber(cmCustomerContactInfoList.get(0).getIdNumber());
            mrCustomerInfo.setSpouseCompanyName(cmCustomerContactInfoList.get(0).getCompanyName());
            mrCustomerInfo.setSpouseHomePhone(cmCustomerContactInfoList.get(0).getMobile());
            mrCustomerInfo.setSpouseOccuption(cmCustomerContactInfoList.get(0).getOccuption());
        }
        mrCustomerInfo.setCustType("1");//借款人
        mrCustomerInfo.setInputDate(secondLevel.getCreateTime());

        customerDataBean.setMrCustomerInfo(mrCustomerInfo);
        return customerDataBean;
    }

    @Override
    public void saveCustomerDate(CustomerDataBean customerDataBean) {
        if(customerDataBean.getFlag() == 0 ){
            mrCustomerInfoMapper.insertSelective(customerDataBean.getMrCustomerInfo());
        }else{
            extMrCustomerInfoMapper.updateByTcc(customerDataBean.getMrCustomerInfo());
        }
    }

    @Override
    public List<MrCustomerInfoRes> getMrCustomersByCusIdOrMobileOrIdNumber(String customerId, String mobile, String idNumber, String tenantId) {
        List<MrCustomerInfo> list=extMrCustomerInfoMapper.selectMrCustomersByCusIdOrMobileOrIdNumber(customerId, mobile,  idNumber,  tenantId);

        return BeanMapping.copyList(list,MrCustomerInfoRes.class);
    }

    @Override
    public MrCustomerInfoRes getMrCustomersByTenantIdAndChannelAndcustomerId(String tenantId, String channel, String customerId) {
        MrCustomerInfo mrCustomerInfo = extMrCustomerInfoMapper.selectMrCustomersByTenantIdAndChannelAndCustomerId(tenantId, channel, customerId);
        return BeanMapping.copy(mrCustomerInfo,MrCustomerInfoRes.class);
    }
}
